﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoolCode;
using CoolCode.Linq;
using CoolCode.Web;
using CoolCode.Web.Mvc;
using XNoteBook.Entities;
using XNoteBook.Services;
using XNoteBook.Models;

namespace XNoteBook.UI.Controllers
{
	public class PostController : CoolCode.Web.Mvc.ControllerBase
	{
		private IPostService _PostService;
		public IPostService PostService
		{
			get
			{
				if (_PostService == null)
				{
					_PostService = Digger.Dig<IPostService>();
				}
				return _PostService;
			}
		}

		public PostController()
		{

		}

		public ActionResult Index()
		{
			string id = this.ValueOf<string>("id", Util.RootID);
			if (!this.Request.IsAjaxRequest())
			{
				Category category = this.PostService.GetCategory(id);
				if (category != null)
				{
					Title = Utility.HtmlEncode(category.Title);
				}
			}

			//var model =new PostIndexModel();
			//model.ParentList= this.PostService.GetSelfAndForefathers(id);
			return View();
		}

		//public  ActionResult PostList(int? page)
		//{
		//    var model =this.PostService.PagingPost(new PageParam( page.GetValueOrDefault() ));
		//    return PartialView(model); 
		//}

		public ActionResult PostPanel()
		{
			return PartialView();
		}

		public ActionResult PostList(string q)
		{
			IQueryBuilder<NodeModel> qBuilder = QueryBuilder.Create<NodeModel>();
			string parentID = this.ValueOf<string>("id", Util.RootID);
			//string qWord = this.ValueOf<string>("q");
			if (string.IsNullOrEmpty(q))
			{
				qBuilder.Equals(c => c.ParentID, parentID);
			}
			else
			{
				qBuilder.Like(c => c.Title, q);
			}

			var model = this.PostService.QueryNode(qBuilder);
			return PartialView(model);
		}

		public ActionResult UrlAddress()
		{
			string id = this.ValueOf<string>("id", Util.RootID);
			var model = this.PostService.GetSelfAndForefathers(id);
			return View(model);
		}

		public ActionResult List()
		{
			return View();
		}

		public ActionResult New(string parentID)
		{
			string id = Util.GenerateUID();
			this.PostService.SaveNode(new NodeModel
			{
				NodeID = id,
				Type = NodeType.Post,
				Title = "新建文件",
				ParentID = parentID,
				CreateTime = DateTime.Now,
				CreateUserID = User.Identity.Name,
				CreateUserName = User.Identity.Name,
				SortIndex = -1
			});
			return RedirectToAction("Edit", new { id = id });
		}

		public ActionResult Edit(string id)
		{
			var model = this.PostService.GetPost(id);
			Title = model.Title;
			ViewData["Title"] = model.Title;
			return View(model);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Edit()
		{
			Post model = new Post();
			model.PostID = this.ValueOf<string>("ID");
			model.Title = this.ValueOf<string>("Title");
			model.Html = this.ValueOf<string>("Html");
			model.Text = model.Html.HtmlToText().Cut(1000);
			model.Summary = model.Text.Cut(200);
			model.UpdateUserID = User.Identity.Name;
			model.UpdateUserName = User.Identity.Name;
			model.UpdateTime = DateTime.Now;

			this.PostService.UpdatePost(model.PostID, c => new Post
			{
				//Title = model.Title,
				Html = model.Html,
				Text = model.Text,
				Summary = model.Summary,
				UpdateUserID = User.Identity.Name,
				UpdateUserName = User.Identity.Name,
				UpdateTime = DateTime.Now,
			});

			if (Request.IsAjaxRequest())
			{
				return this.Success();
			}
			else
			{
				return View(model);
			}
		}

		[ValidateInput(false)]
		public ActionResult UpdateTitle(string id, string title)
		{
			Post model = new Post();
			model.PostID = id;
			model.Title = title;

			this.PostService.UpdatePost(model.PostID, c => new Post
			{
				Title = model.Title,
				UpdateUserID = User.Identity.Name,
				UpdateUserName = User.Identity.Name,
				UpdateTime = DateTime.Now,
			});

			return this.Success();
		}

		public ActionResult Delete()
		{
			try
			{
				string id = this.ValueOf<string>("id");
				if (string.IsNullOrEmpty(id))
				{
					return this.Fail("不能删除根节点");
				}

				this.PostService.DeleteNode(id);
				return this.Success();
			}
			catch (Exception ex)
			{
				return this.Fail(ex.Message);
			}
		}

		public ActionResult Details(string id)
		{
			Post model = this.PostService.GetPost(id);
			if (model == null)
			{
				return RedirectToError("你访问的随笔不存在！");
			}
			Title = model.Title;
			this.PostService.ViewPost(id, User.Identity.Name);
			return View(model);
		}

		public ActionResult Preview(string id)
		{
			Post model = this.PostService.GetPost(id);
			if (model == null)
			{  
				return  View("FolderPreview", "Preview" );
				//return RedirectToAction("FolderPreview", new { id = id  });
				 
				//return Error("你访问的随笔不存在！");
			}

			return View("Details", "Preview", model);
		}

		public ActionResult FolderPreview(string id)
		{ 
			return View();
		}

		public ActionResult SearchWidget()
		{
			return PartialView();
		}


		/*
		public ActionResult BreakZone(NodeModel m)
		{
			return View(m);
		}
		public ActionResult Title(NodeModel m)
		{
			return View(m);
		}

		public ActionResult Operator(NodeModel m)
		{
			return View(m);
		}
		*/

		#region Tree

		[HttpPost]
		public ActionResult EditTree(string operation)
		{
			var request = Request.Form;
			string parentID = request["ref"];
			string id = request["id"];
			string title = request["title"];
			string position = request["position"];
			string type = request["type"];
			string copy = request["copy"];

			switch (operation)
			{
				case "move_node":
					TreeCategory node = new TreeCategory();
					node.NodeID = id;
					node.ParentID = parentID;
					node.SortIndex = Convert.ToInt32(position);
					bool isCopy = (copy == "1");
					this.PostService.MoveNode(node, isCopy);
					break;

				case "create_node":
					id = Util.GenerateUID();
					this.PostService.SaveNode(new NodeModel
					{
						NodeID = id,
						Type = Enum<NodeType>.FindByAttachedString(type),
						Title = title,
						ParentID = parentID,
						CreateTime = DateTime.Now,
						CreateUserID = User.Identity.Name,
						CreateUserName = User.Identity.Name,
						SortIndex = Convert.ToInt32(position)
					});
					break;

				case "remove_node":
					this.PostService.DeleteNode(id);
					break;

				case "rename_node":
					this.PostService.RenameNode(new NodeModel
					{
						NodeID = id,
						Type = Enum<NodeType>.FindByAttachedString(type),
						Title = title
					});
					break;
			}

			return Json(new { status = 1, id = id });
		}

		public ActionResult GetTree(string parentID)
		{
			var model = PostService.GetChildrenNodes(parentID);

			var jsonData = model.Items.Select(c => new
			{
				attr = new
				{
					id = c.NodeID,
					rel = c.Type.GetAttachedString(),//string.IsNullOrEmpty(parentID) ? "drive" : (c.IsCategory ? "folder" : "default"),
					position = c.SortIndex
				},
				data = c.Title,
				state = c.IsLeaf ? "opened" : "closed"
			}).ToList();

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}

		public ActionResult GetCategories(string parentID)
		{
			var model = PostService.GetCategories(parentID);

			var jsonData = model.Items.Select(c => new
			{
				attr = new
				{
					id = c.NodeID,
					rel = c.Type.GetAttachedString(), 
					position = c.SortIndex
				},
				data = c.Title,
				state = c.IsLeaf ? "opened" : "closed"
			}).ToList();

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}

		#endregion
	}
}
